<template>
  <div>
    <el-dialog
      v-model="createVisible"
      :title="operation == 'create' ? '添加配置字段' : '编辑配置字段'"
      @before-ok="createOk"
      @close="close(createRef)"
      width="800px"
      top="100px"
    >
      <el-form
        :model="createForm"
        ref="createRef"
        :rules="createRules"
        label-width="140px"
        size="default"
      >
        <el-form-item label="配置分类：" prop="config_tab_id">
          <el-select v-model="createForm.config_tab_id">
            <el-option
              v-for="item in parentTree"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型：" prop="type">
          <el-radio-group v-model="createForm.type" size="default">
            <el-radio-button v-for="item in typeEnum"
              :key="item.value" :label="item.value">{{item.name}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="表单类型："
          prop="input_type"
          v-if="createForm.type == 'text'"
        >
          <el-select v-model="createForm.input_type">
            <el-option
              v-for="item in inputTypeEnum"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配置名称：" prop="config_name">
          <el-input
            v-model="createForm.config_name"
            placeholder="请输入配置名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="字段变量：" prop="name_field">
          <el-input
            v-model="createForm.name_field"
            placeholder="请输入字段变量"
          ></el-input>
        </el-form-item>
        <el-form-item label="配置简介：" prop="desc">
          <el-input
            v-model="createForm.desc"
            placeholder="请输入配置简介"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="配置参数："
          prop="parameter"
          v-if="
            createForm.type == 'radio' ||
            createForm.type == 'checkbox' ||
            createForm.type == 'select'
          "
        >
          <el-input
            v-model="createForm.parameter"
            type="textarea"
            placeholder="参数方式例如:\n1=>白色\n2=>红色\n3=>黑色"
          ></el-input>
        </el-form-item>
        <el-form-item label="规则：" prop="required" v-if="createForm.type != 'system'">
          <el-input
            v-model="createForm.required"
            type="textarea"
            placeholder="请输入规则"
          ></el-input>
          <help>多个以;分开如:required:true;min:0</help>
        </el-form-item>
        
        <el-form-item
          label="上传类型："
          prop="upload_type"
          v-if="createForm.type == 'upload'"
        >
          <el-radio-group v-model="createForm.upload_type">
            <el-radio label="1" size="default" border>单图</el-radio>
            <el-radio label="2" size="default" border>多图</el-radio>
            <el-radio label="3" size="default" border>文件</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="值：" prop="value" v-if="createForm.type != 'system'">
          <el-input
            v-model="createForm.value"
            placeholder="请输入值"
          ></el-input>
        </el-form-item>

        <el-form-item label="状态：" prop="status" v-if="createForm.type != 'system'">
          <el-radio-group v-model="createForm.status">
            <el-radio v-for="item in StatusEnum" :key="item.value" :label="item.value">{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序：" prop="sort" v-if="createForm.type != 'system'">
          <el-input-number
            v-model="createForm.sort"
            :min="0"
            :max="10000"
            size="default"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="flex center">
          <el-button @click="createVisible = false">取消</el-button>
          <el-button type="primary" @click="createOk(createRef)" :loading="btnLoading" :disabled="btnLoading"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default {
  name:"systemConfigCreate"
}
</script>
  <script lang="ts" setup>
import { ref, h, reactive, getCurrentInstance, nextTick } from "vue";
import type { FormInstance } from "element-plus";
import { useConfig } from "@/store";

import {
  getConfigTabSelectTree,
  createConfig,
  updateConfig,
  getConfigDetail,
} from "@/api/system/config";
import type { Result,ResultError } from "@/types";
const {
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const configStore = useConfig();

const emit = defineEmits(["success"]);

const operation = ref("create");

const operationId = ref(0);
const createVisible = ref(false);
const createRef: any = ref<typeof FormInstance>();
const createForm = ref({
  config_tab_id: 0,
  type: "text",
  input_type: "",
  config_name: "",
  name_field: "",
  desc: "",
  value: "",
  parameter: "",
  required: "",
  upload_type: 1,
  status: 1,
  sort: 0,
});

const StatusEnum = ref(configStore.getEnumItem("StatusEnum"));
const typeEnum = ref(configStore.getEnumItem("system.config.TypeEnum"));
const inputTypeEnum = ref(configStore.getEnumItem("system.config.InputTypeEnum"));

const createRules: any = reactive({
  config_name: [
    {
      required: true,
      message: "配置名称不能为空",
      trigger: "blur",
    },
  ],
  name_field: [
    {
      required: true,
      message: "字段变量不能为空",
      trigger: "blur",
    },
  ],
});

const open = (id = 0) => {
  if (id != 0) {
    operation.value = "update";
    operationId.value = id;
  } else {
    operation.value = "create";
  }
  nextTick(() => {
    toInit();
  });
  createVisible.value = true;
};

const toInit = () => {
  initCascader();
  if (!operationId.value) {
    return;
  }
  getConfigDetail({id:operationId.value})
    .then((res:Result) => {
      createForm.value.config_tab_id = res.data.config_tab_id;
      createForm.value.type = res.data.type.value;
      createForm.value.input_type = res.data.input_type.value || '';
      createForm.value.config_name = res.data.config_name;
      createForm.value.name_field = res.data.name_field;
      createForm.value.desc = res.data.desc;
      createForm.value.value = res.data.value;
      createForm.value.parameter = res.data.parameter;
      createForm.value.required = res.data.required;
      createForm.value.status = res.data.status.value;
      createForm.value.sort = res.data.sort;
    })
    .catch((err:ResultError) => {
      $utils.errorMsg(err);
    });
};

const btnLoading = ref(false)

const createOk = async (formEl:typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid:any, fields: any) => {
    if (valid) {
      if(btnLoading.value){
        return
      }
      btnLoading.value = true
      let operationApi: any = null;
      if (operation.value == "create") {
        operationApi = createConfig(createForm.value);
      } else {
        operationApi = updateConfig(Object.assign({
          id:operationId.value
        },createForm.value));
      }
      operationApi
        .then((res: Result) => {
          $message.success(res.message);
          close(formEl);
          emit("success");
          btnLoading.value = false
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          btnLoading.value = false
        });
    }
  });
};

const createLoading: any = ref(false);

const parentTree: any = ref([]);
const initCascader = () => {
  let obj: any = {};
  if (operationId.value) {
    obj["pid"] = operationId.value;
  }
  getConfigTabSelectTree(obj)
    .then((res: Result) => {
      parentTree.value = res.data;
    })
    .catch((err: ResultError) => {
      createLoading.value = false;
      $utils.errorMsg(err);
    });
};

const close = async (formEl:typeof FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  operationId.value = 0;
  createVisible.value = false;
};

defineExpose({ open });
</script>
  